﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Code.Models;
using System.Configuration;
using System.Data.Common;


namespace Code.Models
{
    public class DBHelper
    {
        /// <summary>
        /// 数据源
        /// </summary>
        internal static DBContext DBContext
        {
            get
            {
                return new DBContext(GetConnectionString());
                //return new DBContext();
            }
        }

        public static DbConnection Connection
        {
            get 
            {
                DbProviderFactory f = System.Data.Common.DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings["DBContext"].ProviderName);
                var con=f.CreateConnection();
                con.ConnectionString = GetConnectionString();
                return con;
            }
        }

        private static log4net.ILog Log = Commen.Log.GetLog(typeof(DBHelper));

        private static string GetConnectionString()
        {
            string connectionString = "";

            string constrtype = ConfigurationManager.AppSettings["ConType"];
            //获取config  ConnectionStrings的配置节
            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["DBContext"];
            string constr = setting.ConnectionString;

            if (constrtype != "0")
            {
                try
                {
                    var des = new Code.Commen.DES();
                    //解密
                    connectionString = des.DecryptString(constr);
                }
                catch (Exception e)
                {
                    if (Log.IsDebugEnabled)
                        Log.Debug(e.Message, e);
                    if (Log.IsWarnEnabled)
                        Log.Warn("连接字符串格式不正确！");

                }
            }
            else
            {
                connectionString = constr;
            }
            return connectionString;
        }
    }
}
